package com.mcp.converter.domain.parser;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.mcp.converter.shared.response.analysis.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * XML解析器抽象基类
 */
public abstract class AbstractXMLParser {
    protected final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 从文件路径中提取文件名
     */
    public String extractFileNameFromPath(String path) {
        if (path == null || path.isEmpty()) {
            return "";
        }
        int lastSeparator = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
        return lastSeparator >= 0 ? path.substring(lastSeparator + 1) : path;
    }

    /**
     * 构建目录分析错误响应
     */
    public String buildDirectoryAnalysisErrorResponse(String directoryPath, boolean recursive,
                                                     long startTime, String errorMessage) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            ObjectNode response = mapper.createObjectNode();
            response.put("success", false);
            response.put("directoryPath", directoryPath);
            response.put("recursive", recursive);
            response.put("error", errorMessage);
            response.put("analyzeDuration", System.currentTimeMillis() - startTime);
            response.put("timestamp", LocalDateTime.now().toString());
            return mapper.writeValueAsString(response);
        } catch (JsonProcessingException e) {
            return "{\"success\": false, \"error\": \"构建错误响应失败\"}";
        }
    }

    /**
     * 扫描XML文件
     */
    public abstract List<String> scanXmlFiles(String directoryPath, boolean recursive);

    /**
     * 从XML文件中提取SQL语句
     */
    public abstract String extractSQLsFromXML(String xmlFilePath);

    /**
     * 执行后备兼容性检查
     */
    public abstract FallbackCompatibilityResult performFallbackCompatibilityCheck(
        List<String> sqls, BatchAnalysisResponse batchResult);

    /**
     * 执行智能重分类
     */
    public abstract CompatibilityReclassificationResult performIntelligentReclassification(
        BatchAnalysisResponse batchResult, List<String> validSqls);

    /**
     * 检查SQL是否包含不兼容函数
     */
    public abstract boolean containsIncompatibleFunctions(String sql);
}
